var ids, input;
var step = 1;
var data = document.location.href;
data = data.split("=")[1];
var i;
init();
function init() {
  var data = document.location.href;
  data = data.split("=")[1];
  var i;
  goodsList.forEach(function (item) {
    if (item.id == data) {
      i = item;
    }
  });
  var div = ce("div", {
    width: "120px",
    height: "22px",
    position: "absolute"
  });
  createBnList(div);
  cteateInput(div, i);
  var divs = document.getElementsByClassName("list_number");
  console.log(divs);
  divs[0].appendChild(div);
}

function createBnList(parent) {
  var leftBn = ce("div", {
    width: "30px",
    height: "30px",
    fontSize: "18px",
    lineHeight: "30px",
    position: "absolute",
    textAlign: "center",
    border: "1px solid #CCCCCC"
  });
  var rightBn = leftBn.cloneNode(false);
  leftBn.style.left = "0px";
  rightBn.style.right = "0px";
  leftBn.textContent = "-";
  rightBn.textContent = "+";
  parent.appendChild(leftBn);
  parent.appendChild(rightBn);
  leftBn.addEventListener("mousedown", mouseHandler);
  rightBn.addEventListener("mousedown", mouseHandler);
  leftBn.addEventListener("click", clickHandler);
  rightBn.addEventListener("click", clickHandler);
}

function cteateInput(parent, i) {
  input = ce("input", {
    width: "60px",
    height: "30px",
    position: "absolute",
    left: "30px",
    border: "none",
    textAlign: "center",
    borderTop: "1px solid #CCCCCC",
    borderBottom: "1px solid #CCCCCC"
  });
  input.value = "1";
  parent.appendChild(input);
  input.addEventListener("input", inputHandler);
}

function mouseHandler(e) {
  e.preventDefault();
}

function inputHandler(e) {
  //    限制输入非数字
  this.value = this.value.replace(/\D/g, "");
  // 节流
  if (ids) return;
  ids = setTimeout(
    function (input) {
      clearTimeout(ids);
      ids = 0;
      setStep(input.value);
    },
    500,
    this
  );
}

function clickHandler(e) {
  if (this.textContent === "-") {
    setStep(step - 1);
  } else {
    setStep(step + 1);
  }
}

function setStep(value) {
  value = Number(value);
  if (value < 1) value = 1;
  if (value > 999) value = 999;
  step = value;
  input.value = step;
  i.number = input.value;
}
function ce(type, style) {
  var elem = document.createElement(type);
  Object.assign(elem.style, style);
  return elem;
}
